import { AmqpClientService } from '@app/amqp-client';
import { CacheService } from '@app/cache';
import { ConfigureService } from '@app/configure';
import { DeviceRepositoryService } from '@app/db/device-repository/device-repository.service';
import { Injectable, OnModuleInit } from '@nestjs/common';
import * as dayjs from 'dayjs';

@Injectable()
export class AmqpService implements OnModuleInit{
	private DEVICE_MESSAGE_LIST:string
	private DEVICE_MSG_OF_IOT_KEY:string
	private DEVICE_MSG_OF_REPORT_KEY:string

	constructor(
		private readonly device:DeviceRepositoryService,
		private readonly amqpClient:AmqpClientService,
		private readonly config:ConfigureService,
		private readonly cache:CacheService,
	) {
		//this.DEVICE_MESSAGE_LIST = this.config.get('DEVICE_MESSAGE_LIST')

		this.DEVICE_MSG_OF_IOT_KEY = this.config.get('DEVICE_MSG_OF_IOT_KEY')
		this.DEVICE_MSG_OF_REPORT_KEY = this.config.get('DEVICE_MSG_OF_REPORT_KEY')
		
	}
	onModuleInit() {
		this.amqpClient.on('message', (context) => {
			context.delivery.accept();

			var msg = context.message;

			console.log(msg.application_properties.topic)
			console.log(msg.body.content.toString())


			

			// var msg = context.message;
			// const topic = msg.application_properties.topic
			// const messageId = msg.message_id

			// Buffer.from(msg.body.content).toString()

			// if(topic.indexOf('/as/mqtt/status') == 0) {

			// }

			const time = Math.floor(Date.now() / 1000)

			if(msg.application_properties.topic.indexOf('/as/mqtt/status') == 0) {
				try {

					const data = JSON.parse(msg.body.content.toString())
					const deviceId = Number(data.deviceName)

					if(data.status == 'online') {
						this.device.update({id : deviceId}, {connectStatus : 1})
					}else if(data.status == 'offline') {
						this.device.update({id : deviceId}, {connectStatus : 0, offlineTime : time})
					}
					
				} catch (error) {
					
				}

				//this.cache.client.lpush(this.DEVICE_MSG_OF_IOT_KEY, JSON.stringify({id : deviceId, status : data.status, time : time}))

			}else {
				try {

					this.cache.client.lpush(this.DEVICE_MSG_OF_REPORT_KEY, JSON.stringify({time : time, topic : msg.application_properties.topic, data : msg.body.content.toString()}))
					
				} catch (error) {
					
				}
			}



			context.delivery.accept();
		})

		this.amqpClient.connect()
	}
}
    